package services

import (
	"TaskAssignmentSystem/internal/admin/dao"
	"TaskAssignmentSystem/pkg/db/mysql"
	"TaskAssignmentSystem/pkg/utils"
	"fmt"
	"gorm.io/gorm"
	"math/rand"
	"strings"
)

type SystemProhibitedWordsService struct {
}

func (m *SystemProhibitedWordsService) CheckProhibitedWords(value string) (words []string, isProhibited bool, err error) {
	var prohibitedWordsDao dao.Common[dao.SystemProhibitedWords]
	whereSql := "'" + value + "' like CONCAT('%',prohibited_word,'%')"
	prohibitedWordsDao.CustomWhere = append(prohibitedWordsDao.CustomWhere, whereSql)
	list, err := prohibitedWordsDao.FindAll(map[string]interface{}{})
	if err != nil {
		return words, false, err
	}
	if len(list) == 0 {
		return words, false, err
	}
	for _, word := range list {
		words = append(words, word.ProhibitedWord)
	}
	return words, true, err
}

func (s *SystemProhibitedWordsService) QueryProhibitedWordsPage(prohibitedWord, startTime, endTime string, page, pageSize int64) (int64, []dao.SystemProhibitedWords, error) {
	/*var commonServe CommonService[dao.SystemProhibitedWords]
	commonServe.Page = page
	commonServe.PageSize = pageSize
	if startTime != "" && endTime == "" {
		commonServe.WhereStr = append(commonServe.WhereStr, fmt.Sprintf("left(created_at,10) >= '%v'", startTime))
	} else if startTime == "" && endTime != "" {
		commonServe.WhereStr = append(commonServe.WhereStr, fmt.Sprintf("left(created_at,10) <= '%v'", endTime))
	} else if startTime != "" && endTime != "" {
		commonServe.WhereStr = append(commonServe.WhereStr, fmt.Sprintf("left(created_at,10) >= '%v' and left(created_at,10) <= '%v'", startTime, endTime))
	}
	if prohibitedWord != "" {
		commonServe.WhereStr = append(commonServe.WhereStr, fmt.Sprintf("prohibited_word LIKE '%%%v%%'", prohibitedWord))
	}
	field := fmt.Sprintf("group_no,MAX(group_tag) group_tag,GROUP_CONCAT(prohibited_word) prohibited_word")
	commonServe.SelectField = &field
	commonServe.Group = "group_no"
	commonServe.Order = "group_no"
	if res, err := commonServe.SelectList(); err != nil {
		return 0, nil, err
	} else {
		return res.Total, res.Data, nil
	}*/
	var commonServe dao.Common[dao.SystemProhibitedWords]
	where := ""
	if startTime != "" && endTime != "" {
		where += fmt.Sprintf("and left(created_at,10) >= '%v' and left(created_at,10) <= '%v' ", startTime, endTime)
	}
	if prohibitedWord != "" {
		where += fmt.Sprintf("and prohibited_word LIKE '%%%v%%' ", prohibitedWord)
	}
	sql := fmt.Sprintf(" SELECT group_no,MAX(group_tag) group_tag,GROUP_CONCAT(prohibited_word SEPARATOR '，') prohibited_word,created_at FROM `tas_system_prohibited_words` where 1=1 %v GROUP BY `group_no` ORDER BY group_no %v ", where, utils.Limit(page, pageSize))
	countSql := fmt.Sprintf("select count(*) as total from ( SELECT group_no,MAX(group_tag) group_tag,GROUP_CONCAT(prohibited_word SEPARATOR '，') prohibited_word FROM `tas_system_prohibited_words` where 1=1 %v GROUP BY `group_no` ORDER BY group_no ) a ", where)
	if list, err := commonServe.RawList(sql); err != nil {
		return 0, nil, err
	} else {
		if num, err := commonServe.RawCount(countSql, "total"); err != nil {
			return 0, nil, err
		} else {
			return num, list, nil
		}
	}
}

func (s *SystemProhibitedWordsService) ProhibitedWordsBatchDel(groupNos []string) error {
	var commonServe dao.Common[dao.SystemProhibitedWords]
	if len(groupNos) > 0 {
		//传了group_no删除对应group_no的
		if err := commonServe.BatchDeleteByStringColumn("group_no", groupNos).Error; err != nil {
			return err
		}
		return nil
	} else {
		//没传group_no删除所有
		if list, err := commonServe.FindAll(map[string]interface{}{}); err != nil {
			return err
		} else {
			var canDelIds []uint
			for _, model := range list {
				canDelIds = append(canDelIds, model.Id)
			}
			if err := commonServe.RemoveUnscopedWhere(map[string]interface{}{"id": canDelIds}).Error; err != nil {
				return err
			} else {
				return nil
			}
		}
	}
}

func (s *SystemProhibitedWordsService) BatchImportProhibitedWords(words []*dao.SystemProhibitedWords) error {
	_db := mysql.GetDB()
	return _db.Transaction(func(tx *gorm.DB) error {
		var orderReviewDao dao.Common[dao.SystemProhibitedWords]
		orderReviewDao.Tx = tx
		if err := tx.Create(words).Error; err != nil {
			return err
		}
		return nil
		/*for _, word := range words {
			if err := tx.Model(word).Create("order_id = ?", order.OrderId).C(order).Error; err != nil {
				return err
			}
		}
		return nil*/
	})
}

func (s *SystemProhibitedWordsService) BatchDelProhibitedWords(words []*dao.SystemProhibitedWords) error {
	_db := mysql.GetDB()
	return _db.Transaction(func(tx *gorm.DB) error {
		var orderReviewDao dao.Common[dao.SystemProhibitedWords]
		orderReviewDao.Tx = tx
		canDelWordsList := make([]string, len(words))
		for i, word := range words {
			canDelWordsList[i] = word.ProhibitedWord
		}
		if err := orderReviewDao.BatchDeleteByStringColumn("prohibited_word", canDelWordsList).Error; err != nil {
			return err
		}
		return nil
	})
}

func (s *SystemProhibitedWordsService) GenerateRandomNickName(lenNum int) string {
	var CHARS = []string{"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z",
		"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z",
		"1", "2", "3", "4", "5", "6", "7", "8", "9", "0"}
	str := strings.Builder{}
	length := len(CHARS)
	for i := 0; i < lenNum; i++ {
		l := CHARS[rand.Intn(length)]
		str.WriteString(l)
	}
	return str.String()
}

func (s *SystemProhibitedWordsService) AlterUserNickNameAndIntroduction() error {
	var prohibitedWordsServe dao.Common[dao.SystemProhibitedWords]
	if list, err := prohibitedWordsServe.FindAll(map[string]interface{}{}); err != nil {
		return err
	} else {
		prohibitedWords := ""
		for i, words := range list {
			if i != len(list)-1 {
				prohibitedWords += words.ProhibitedWord + "|"
			} else {
				prohibitedWords += words.ProhibitedWord
			}
		}
		//先查出昵称违规的用户然后修改
		var userServeNickName CommonService[dao.SystemUser]
		userServeNickName.WhereStr = append(userServeNickName.WhereStr, fmt.Sprintf("nick_name REGEXP '%v'", prohibitedWords))
		if userNickNameList, err := userServeNickName.FindAll(); err != nil {
			return err
		} else {
			for _, user := range userNickNameList {
				userServeNickName.Query = map[string]interface{}{"id": user.Id}
				if err := userServeNickName.Update(map[string]interface{}{"nick_name": s.GenerateRandomNickName(10)}); err != nil {
					return err
				}
			}
		}
		//再查出简介违规的用户然后修改
		var userServeIntroduction CommonService[dao.SystemUser]
		userServeIntroduction.WhereStr = append(userServeIntroduction.WhereStr, fmt.Sprintf("introduction REGEXP '%v'", prohibitedWords))
		if userIntroductionList, err := userServeIntroduction.FindAll(); err != nil {
			return err
		} else {
			for _, user := range userIntroductionList {
				userServeIntroduction.Query = map[string]interface{}{"id": user.Id}
				if err := userServeIntroduction.Update(map[string]interface{}{"introduction": "无"}); err != nil {
					return err
				}
			}
		}
	}
	return nil
}
